<template>
    <div style="padding: 20px;height: 100vh">
        <div class="social-container">
            <div class="social-left">
                <div class="object-list-title">社交列表</div>
               
                <div class="object-list">
                    <div class="deep-input">
                        <el-input v-model="search" placeholder="搜索用户" @clear="userList = [];getBuddyList()" clearable @keyup.enter.native="searchUser()"></el-input>
                    </div>
                    <div class="search-data-list" v-if="search !=''">
                        <el-empty description="暂无搜索内容~" v-if="!userList||userList.length === 0"></el-empty>
                        <div class="data-item" v-for="(user,index) in userList" :key="index">
                            <div class="user-info-main">
                                <div class="user-avatar">
                                    <el-tooltip class="item" effect="dark" :content="user.username" placement="top">
                                        <el-avatar :size="50" :src="user.avatar"></el-avatar>
                                    </el-tooltip>
                                    
                                </div>
                                <div class="user-info" >
                                    <div style="font-weight: 600;width: 80px;" class="text-display-a-line">{{ user.nickname }}</div>
                                    <div style="font-size: 14px;font-weight: 400;color: #999;width: 80px;" class="text-display-a-line">{{ user.username }}</div>
                                </div>
                            </div>
                            
                            <div class="follow" @click="followOrUnfollow(user)">
                                {{ user.follow?'取消关注':'关注' }}
                            </div>
                        </div>
                        <!-- <div style="cursor: pointer;color: #999;display: flex;justify-content: center;" @click="goPage()" v-if="page.records.length>0">查看更多</div> -->
                    </div>
                    <div class="chat-object-list" v-else>
                        <div 
                        :class="chat.active != index?'chat-object-item':'active-chat-object-item'"  
                        v-for="(item,index) in buddyList" 
                        :key="index"
                        @click="getChatInfo(index)"
                        >
                            <div class="">
                                {{ item.nickname }}
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <div class="social-right ">
                <div class="object-info">{{ chat.receiver.nickname }}</div>
                <div class="chat-info" >

                    <div v-for="(record,index) in chat.receiver.chatRecords" :key="index" >

                        <!-- 当前用户名等于发送者的用户名，标识是当前用户 -->
                        <div class="chat-item-right"  v-if="chat.receiver.chatRecords&&chat.sender.username === record.sender ">

                       
                            <div style="display: flex;justify-content: flex-end;">
                                <div class="chat-content" >{{ record.message }}</div>
                            </div>

                        </div>
                        <div class="chat-item" v-else>
                            <div >
                                <div class="chat-username"> {{ chat.receiver.nickname }}</div>
                                <div class="chat-content"> {{ record.message }}</div>

                            </div>

                        </div>
                    </div>
                    
                    
                   
                    

                </div>
                <div class="chat-input input-deep">
                    <el-input type="textarea" v-model="chat.content" placeholder="请输入..." :disabled="!chat.receiver" />
                    
                </div>
                    <div style="display: flex;justify-content: flex-end;">
                        <i-button level="info" @click.native="sendMessage">发送消息</i-button>
                    </div>
                
            </div>
        </div>
    </div>
</template>

<script>
import IButton from '@/components/plugs/i-button/IButton.vue'
import {post,get} from '@/utils/api.js'



export default {
    data(){
        return{
            chat:{
                content:'',
                sender:{},
                receiver:{},
                active:0,
                websocket:null
                
            },
            search:'',
            buddyList:[],//好友列表
            userList:[]
        }
    },
    methods:{
        initWebSocket(){
            let auth = localStorage.getItem('token');
            let token = auth.replace('bearer ','');
            let url = `wss://api.sns.qugeek.com/base-chat/chat/message/${token}?Authorization=${auth}`
            // let url = `ws://localhost:8610/chat/message?Authorization=${token}`
            this.chat.websocket = new WebSocket(url);
            console.log(this.chat.websocket.readyState)
            this.chat.websocket.onopen = this.openMessage;
            this.chat.websocket.onmessage = this.onMessage;
            this.chat.websocket.onerror = this.onError;
            this.chat.websocket.onclose = this.onClose;

            

        },
        getChatInfo(index){ //获取与好友的聊天记录
            this.chat.active = index;
            this.chat.receiver = JSON.parse(JSON.stringify(this.buddyList[index]));
            //获取聊天记录
            const promise = get({
                url:'/base-chat/chat/user/records',
                params:{receiverUserId:this.chat.receiver.id}
            });

            promise.then(res=>{
                if(res&&res.code === 200){
                    console.log(res.data)
                    this.$nextTick(()=>{
                        this.$set(this.chat.receiver,'chatRecords',res.data)
                    })
                    
                }
            })
            


        },
        openMessage(){
            console.log('打开了一个连接');
        },
        sendMessage(){ //发送信息
            const content = this.chat.content;

            let chatRecord = {sender:this.chat.sender.username,receiver:this.chat.receiver.username,message:content}
            this.chat.content = '';
            let websocketMessage = JSON.stringify(chatRecord);
            let message = JSON.parse(websocketMessage);
            this.chat.websocket.send(websocketMessage)
           
            this.chat.receiver.chatRecords.push(message)
            
            
        },
        onMessage(evt){//接收消息
            console.log('evt',evt);
            let data = JSON.parse(evt.data);
            console.log('data',data)
            this.$nextTick(()=>{
               
                this.chat.receiver.chatRecords.push(data);
            })
            
        },
        onError(){
            console.log('连接失败~');
        },
        onClose(evt){
            console.log('连接关闭~',evt.code);
            
        },
        getBuddyList(){//获取好友列表
            const promise = get({
                url:'/base-user/front/user/relation/buddy/list',
            });

            promise.then(res=>{
                if(res&&res.code === 200){
                    this.buddyList = res.data;
                    if(this.buddyList.length>0){
                        this.getChatInfo(0);
                    }
                    
                }
            })

        },
        getUserInfo(){//获取发送者信息
            const promise = get({
                url:'/base-user/front/user/details'
            });

            promise.then(res=>{
                if(res&&res.code === 200){
                    this.chat.sender = res.data;
                }
            })

        },
        searchUser(){
            // 搜索用户
            const promise = get({
                url:'/base-user/front/user/search',
                params:{searchValue:this.search}
            });

            promise.then(res=>{
                console.log('res',res);
                if(res&&res.code === 200){
                    this.userList = res.data;
                }
            })
        },
        followOrUnfollow(row){
            // 关注或取消关注
            const promise = post({
                url:'/base-user/front/user/relation/follow-or-unfollow',
                data:{followUserId:row.id}
            });

            promise.then(res=>{
                if(res){
                    if(res.code === 200){
                        this.$message.success(res.message);
                        this.searchUser();
                        this.getBuddyList();
                        return;
                    }
                    this.$message.error(res.message);
                }
            })
        }

    },
    components:{
        IButton

    },
    created(){
        //初始化websocket
        this.initWebSocket();
        //获取好友列表
        this.getBuddyList();
        //获取当前用户信息
        this.getUserInfo();
        

    },
    beforeDestroy(){
        this.chat.websocket.close();
    }

}
</script>

<style scoped>
.social-container{
    
    display: flex;
    justify-content: space-between;
   
    
}
.social-left{
   
    width: 30%;
}
.object-list-title{
    /* font-size: 20px; */
    font-weight: 600;
    padding: 10px;
    border-bottom: 1px solid #dcdfe6;

}
.object-list{
    height: 760px;
    overflow: hidden scroll;
    /* background-color: rgb(245, 245, 245); */
}
.social-right{
    width: 70%;
    border-left: 1px solid #dcdfe6;
}


.input-deep>>>textarea{
    height: 140px;
    resize:none;
    /* border-top: 1px solid #dcdfe6; */
    border-radius: 0;
    border: 0;
}
.chat-info{
    background-color: rgb(245, 245, 245);
    height: 460px;
    overflow: hidden scroll;
    padding-bottom: 100px;
}
.chat-input{
    border-top: 1px solid #dcdfe6;
    width: 100%;
    display: flex;
    justify-content: center;
    padding-top: 15px;
}
.object-info{
    height: 40px;
    line-height: 40px;
   padding-left: 10px;
   padding-bottom: 5px;
   
    font-weight: 600;
    border-bottom: 1px solid #dcdfe6;
    position: relative;
}
.chat-item{
    
    padding: 10px;
    display: flex;
    justify-content: flex-start;
    /* width:480px;
    word-wrap: break-word; */
   
}
.chat-item-right{
    padding: 10px;
    display: flex;
    justify-content: flex-end;
    /* width:480px;
    word-wrap: break-word; */
}

.chat-content,.chat-username{
    min-height: 40px;
    line-height: 40px;
    
   
}
.chat-username{
    font-size: 14px;
    color: #999;
}
.chat-content{
    margin-left: 10px;
    background-color: #fff;
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 10px;
    max-width: 580px;
    word-wrap: break-word;

}

.data-item{
    display: flex;
    padding: 10px;
    justify-content: space-between;
}
.user-info-main{
    display: flex;
}

.user-info{
    width: 100px;
    margin-left: 10px;
}
.follow{
    line-height: 50px;
    min-width: 64px;
    text-align: center;
   
}

.follow:hover{
    /* background-color: #FF6900; */
    cursor: pointer;
    /* color: #fff; */
    color: #FF6900;
   
}

.deep-input>>>input{

    border-radius: 0;
    border: 0;
}
.deep-input{
    /* border: 1px solid #dcdfe6;
    height: 40px; */

    margin-top: 5px;
    margin-bottom: 5px;
  
}

.chat-object-item:hover{
    cursor: pointer;
    background-color: rgb(245, 245, 245);
    
}
.chat-object-item,.active-chat-object-item{
    height: 40px;
    line-height: 40px;
    padding: 5px;
}
.active-chat-object-item{
    background-color: rgb(245, 245, 245);
}

.active-chat-object-item:hover{
    cursor: pointer;
}


</style>